using Godot;
using System;
using MyKindom.UnitSystem;

namespace MyKindom.StateMachine
{
	public class MoveToPositionState : UnitState
	{
		public new string m_stateName = "MoveToPosition";

		public override void EnterState(UnitBase unit)
		{
			GD.Print("Enter MoveToPositionState");
		}

		public override void LeaveState(UnitBase unit)
		{
			GD.Print("Leave MoveToPositionState");
		}

		public override void UpdataState(UnitBase unit)
		{
			GD.Print("Unit move to target position");

			// 计算距离
			Vector2 startPosition = unit.Position;
			Vector2 endPosition = unit.m_targetPosition;
			float distance = startPosition.DistanceTo(endPosition);
			GD.Print("距离为 ", distance);

			// 判断是否需要移动
			if (distance > 20)
			{
				MoveToTargetPosition(unit, startPosition, endPosition);
			}
			else
			{
				unit.GoBackToLastState();
			}
		}

		// 移动单位
		private void MoveToTargetPosition(UnitBase unit, Vector2 startPosition, Vector2 endPosition)
		{
			Vector2 moveDirection = (endPosition - startPosition).Normalized();
			unit.Position += moveDirection * unit.m_speed * ((float)(unit.GetProcessDeltaTime()));
		}
	}
}
